
#include "usart.h"
#include <stdio.h>
#include <string.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"  
#include "freertos/task.h" 

char RS232_flge=0;


/**
 * @brief       初始化串口
 * @param       baudrate: 波特率, 根据自己需要设置波特率值
 * @note        注意: 必须设置正确的时钟源, 否则串口波特率就会设置异常.
 * @retval      无
 */
void usart_init1(uint32_t baudrate)//232
{
    uart_config_t uart_config;                          /* 串口配置句柄 */

    uart_config.baud_rate = baudrate;                   /* 波特率 */
    uart_config.data_bits = UART_DATA_8_BITS;           /* 字长为8位数据格式 */
    uart_config.parity = UART_PARITY_DISABLE;           /* 无奇偶校验位 */
    uart_config.stop_bits = UART_STOP_BITS_1;           /* 一个停止位 */
    uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;   /* 无硬件控制流 */
    uart_config.source_clk = UART_SCLK_APB;             /* 配置时钟源 */
    uart_config.rx_flow_ctrl_thresh = 122;              /* 硬件控制流阈值 */
    uart_param_config(USART_UX, &uart_config);          /* 配置uart端口 */

    /* 配置uart引脚 */
    uart_set_pin(USART_UX, USART_TX_GPIO_PIN, USART_RX_GPIO_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    /* 安装串口驱动 */
    uart_driver_install(USART_UX, RX_BUF_SIZE * 2, RX_BUF_SIZE * 2, 20, NULL, 0);
}

// An example of echo test with hardware flow control on UART
void usart_init2(void)//485
{
	const int uart_num = ECHO_UART_PORT;
	uart_config_t uart_config = {
		.baud_rate = BAUD_RATE,
		.data_bits = UART_DATA_8_BITS,
		.parity = UART_PARITY_DISABLE,
		.stop_bits = UART_STOP_BITS_1,
		.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		.rx_flow_ctrl_thresh = 122,
		.source_clk = UART_SCLK_DEFAULT,
	};

	ESP_ERROR_CHECK(uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0));

	// Configure UART parameters
	ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));


	// Set UART pins as per KConfig settings
	ESP_ERROR_CHECK(uart_set_pin(uart_num, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));

	// Set RS485 half duplex mode
	ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX));

	// Set read timeout of UART TOUT feature
	ESP_ERROR_CHECK(uart_set_rx_timeout(uart_num, ECHO_READ_TOUT));

}


void RS232_Test(void* arg)
{
    esp_err_t ret;
    uint8_t len = 0;
    uint16_t times = 0;
	
    unsigned char data[RX_BUF_SIZE] = {0};                                                                /* 初始化串口 */

    while(1)
    {
        uart_get_buffered_data_len(USART_UX, (size_t*) &len);                           /* 获取环形缓冲区数据长度 */

        if (len > 0)                                                                    /* 判断数据长度 */
        {
            memset(data, 0, RX_BUF_SIZE);                                               /* 对缓冲区清零 */

			
            uart_read_bytes(USART_UX, data, len, 100);                                  /* 读数据 */

			printf("len  = %d\r\n",len);
			printf("data[0]  = 0X%X\r\n",data[0]);
			printf("data[1]  = 0X%X\r\n",data[1]);
			printf("data[2]  = 0X%X\r\n",data[2]);
			printf("data[3]  = 0X%X\r\n",data[3]);
			printf("data[4]  = 0X%X\r\n",data[4]);
			printf("data[5]  = 0X%X\r\n",data[5]);

            uart_write_bytes(USART_UX, (const char*)data, strlen((const char*)data));   /* 写数据 */
        }
		
		vTaskDelay(10);
    }
}
void RS232Test(void)
{
    esp_err_t ret;
    uint8_t len = 0;
    uint16_t times = 0;
	
    unsigned char data[RX_BUF_SIZE] = {0};                                                                /* 初始化串口 */


        uart_get_buffered_data_len(USART_UX, (size_t*) &len);                           /* 获取环形缓冲区数据长度 */

        if (len > 0)                                                                    /* 判断数据长度 */
        {
            memset(data, 0, RX_BUF_SIZE);                                               /* 对缓冲区清零 */

			
            uart_read_bytes(USART_UX, data, len, 100);                                  /* 读数据 */

			//printf("RS232  = %d%d%d\r\n",data[0],data[1],data[2]);

            uart_write_bytes(USART_UX, (const char*)data, strlen((const char*)data));   /* 写数据 */

			if(data[0]==22 && data[1]==33 && data[2]==22)
			{
				RS232_flge = 1;
			}
        }
		else
		{
			memset(data, 0, RX_BUF_SIZE);
			data[0]=22;
			data[1]=33;
			data[2]=22;
			uart_write_bytes(USART_UX, (const char*)data, strlen((const char*)data));   /* 写数据 */
		
		}
		
		vTaskDelay(10);
    
}

void echo_send(const int port, const char* str, uint8_t length)
 {
	 if (uart_write_bytes(port, str, length) != length) {
		 // add your code to handle sending failure here
		 abort();
	 }
 }
 

void RS485_TxRx(void)
 {
	 unsigned char data[BUF_SIZE];
	 //Read data from UART
	 int len = uart_read_bytes(ECHO_UART_PORT, data, BUF_SIZE, PACKET_READ_TICS);

	 //Write data back to UART
	 if (len > 0) {
		 //echo_send(uart_num, "\r\n", 2);
		 printf("\r\n");
		 printf("	RS485		");
		 printf("[ ");
		 for (int i = 0; i < len; i++) {
			 printf("0x%.2X ", (uint8_t)data[i]);
			 echo_send(ECHO_UART_PORT, (const char*)&data[i], 1);
			 // Add a Newline character if you get a return charater from paste (Paste tests multibyte receipt/buffer)
			 if (data[i] == '\r') {
				 echo_send(ECHO_UART_PORT, "\n", 1);
			 }
		 }
		 printf("] \n");
		 //echo_send(uart_num, "]\r\n", 3);
	 } else {
		 char data1[5] = {0x44,0x88,0x55};
		 echo_send(ECHO_UART_PORT,data1, strlen(data1));
		 ESP_ERROR_CHECK(uart_wait_tx_done(ECHO_UART_PORT, 10));
		 vTaskDelay(500);
	 }
 
}

void RS485_Test(void *arg)
{
	while(1)
	{
		RS485_TxRx();
		vTaskDelay(50);
	}

}

